package com.hm.oauth.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hm.common.common.CommonUtil;
import com.hm.common.exception.ServiceException;
import com.hm.common.model.ResultMessage;
import com.hm.oauth.service.AccessTokenService;
import com.hm.oauth.service.AuthorizeService;
import com.hm.oauth.service.ClientService;
import com.hm.oauth.vo.ClientVo;

/**
 * @author shishun.wang
 * @date 下午5:34:07 2016年8月31日
 * @version 1.0
 * @describe
 */
@Controller
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AccessTokenController {

	@Autowired
	private ClientService clientService;

	@Autowired
	private AuthorizeService authorizeService;

	@Autowired
	private AccessTokenService accessTokenService;

	@RequestMapping(value = "accessToken", method = RequestMethod.POST)
	public @ResponseBody Object accessToken(HttpServletRequest request) {
		try {
			OAuthAuthzRequest authzRequest = new OAuthAuthzRequest(request);

			ClientVo clientVo = clientService.getClinetByClientId(authzRequest.getParam(OAuth.OAUTH_CLIENT_ID));
			if (CommonUtil.isNotEmpty(clientVo)) {
				boolean clientKey = CommonUtil.isNotEmpty(authzRequest.getParam(OAuth.OAUTH_CLIENT_SECRET))
						&& clientVo.getClientSecret().equals(authzRequest.getParam(OAuth.OAUTH_CLIENT_SECRET));
				if (!clientKey) {// 客户端密钥不正确
					throw ServiceException.warn("客户端密匙不正确");
				}
			} else {// 客户端id不存在
				throw ServiceException.warn("客户端不存在");
			}

			String authorizeCode = authzRequest.getParam(OAuth.OAUTH_CODE);
			if (authzRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
				if (CommonUtil.isEmpty(authorizeService.get(authorizeCode))) {// 授权码不正确
					throw ServiceException.warn("授权码不正确");
				}
			}

			OAuthIssuer authIssuer = new OAuthIssuerImpl(new MD5Generator());
			String accessToken = authIssuer.accessToken();
			accessTokenService.put(accessToken, authorizeCode);

			OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
					.setAccessToken(accessToken).setExpiresIn(String.valueOf(3600L)).buildJSONMessage();

			return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
		} catch (Exception e) {
			e.printStackTrace();
			ResultMessage<Object> resultMessage = new ResultMessage<>();
			{
				resultMessage.setMessage(e.getMessage());
			}
			return new ResponseEntity<>(resultMessage, HttpStatus.BAD_REQUEST);
		}
	}

	@RequestMapping(value = "checkAccessToken", method = RequestMethod.POST)
	public @ResponseBody Object checkAccessToken(@RequestParam("accessToken") String accessToken) {

		if (CommonUtil.isNotEmpty(accessTokenService.getAccssToken(accessToken))) {
			ResultMessage<Object> resultMessage = new ResultMessage<>();
			{
				resultMessage.setMessage("accessToken 不存在");
			}
			return new ResponseEntity<>(resultMessage, HttpStatus.UNAUTHORIZED);
		}
		return new ResponseEntity<>(HttpStatus.OK);
	}
}
